package middleware

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"shoping.zozoo.net/tool"
	"strings"
)

func JWTAuth() gin.HandlerFunc {
	return func(c *gin.Context) {
		var (
			token string
			id int64
			err error
		)

		token= c.Request.Header.Get("Authorization")
		token = strings.Replace(token,"Bearer ","",1)
		if token == "" {
			tool.ResponseError(c,http.StatusUnauthorized,"Authorization 不能为空")
			c.Abort()
			return
		}
		if id, err = tool.ValidateToken(token);err != nil {
			tool.ResponseError(c,http.StatusUnauthorized,err.Error())
			c.Abort()
			return
		}

		//将用户id注册在上下文中
		c.Set("user_id",id)

		c.Next()
	}
}
